import React from 'react';
import classNames from 'classnames';
import {MInput,MIcon} from '../MComponent'
import {ComponentTool} from '../Tool/ComponentTool';
import MonthPicker from './MonthPicker';
import RangePicker from './RangePicker';
import moment from 'moment';
moment.locale();
/*
*	调用方式： <DatePicker onChange={this._changePicker} className={'demoClass'}/>
*
*	----------------------------------------------------------------------
*	|    参数     |	      说明	  	   |      类型	   |      默认值	 |
*	----------------------------------------------------------------------
*	|  onChange   |       回调函数 	   |    function   |				 |
*	----------------------------------------------------------------------
*	|  className  |    用户自定义样式    |     string    | 				 |
*	----------------------------------------------------------------------
*	|  initValue  |    用户初始化的时间    |     string    | 				 |
*	----------------------------------------------------------------------
*	|  placeholder  |    输入框中默认的提示    |     string    | 				 |
*	----------------------------------------------------------------------
*/
class DatePicker extends React.Component{
	constructor(props) {
		super(props);
		this.state = {
			view:'DatePicker',										//视图类别:DatePicker,MonthPicker,DecadePicker
			previewView:'DatePicker',
			initValue:this.props.initValue,
			changeViewDate:this._initDate(),
			format:'YYYY-MM-DD',
			dateOpen:false,
			placeholder:this.props.placeholder || '',
		};
		[
			'_initDate',
	        '_showPicker',
	        '_closePicker',
	        '_stopPropagation',
	        '_prevYear',
	        '_prevMonth',
	        '_nextMonth',
	        '_nextYear',
	        '_prevDecade',
	        '_nextDecade',
	        '_prevCentury',
	        '_nextCentury',
	        '_clearDate',
	        '_selectDate',
	        '_selectMonth',
	        '_selectYear',
	        '_selectDecade',
	        '_changeView',
	        '_renderDatePicker',
	        '_renderMonthPicker',
	        '_renderYearPicker',
	        '_renderDecadePicker',
      	].forEach(func=>{
          	this[func] = this[func].bind(this);
      	});
	}
	_initDate(date){
		return moment(date || this.props.initValue || new Date()).format('YYYY-MM-DD');
	}
	_showPicker(e){
		this._stopPropagation(e);
	    // let ifOpen = this.state.dateOpen;
	    this.setState({
      		dateOpen:true
	    }) 
		// 应该要把时间存储下来的
		// console.log('这里需要显示日期插件了');
		// console.log(e.target.value);
	}
	_closePicker(){
		let newState = this.state;
	    if(newState.dateOpen){
	    	newState.dateOpen = false;
	    	newState.view='DatePicker';
	    	newState.changeViewDate = !!newState.initValue && moment(newState.initValue).isValid()?newState.initValue:newState.changeViewDate;
			this.setState(newState)
	    } 
	}
	_stopPropagation(e){
		e.stopPropagation();
		if (e.nativeEvent.stopImmediatePropagation) {
      		e.nativeEvent.stopImmediatePropagation();
	    }
	}
	_prevYear(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).subtract(1,'years'));
		this.setState(newState);
	}
	_prevMonth(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).subtract(1,'months'));
		this.setState(newState);
	}
	_nextMonth(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).add(1,'months'));
		this.setState(newState);
	}
	_nextYear(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).add(1,'years'));
		this.setState(newState);
	}
	_prevDecade(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).subtract(10,'years'));
		this.setState(newState);
	}
	_nextDecade(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).add(10,'years'));
		this.setState(newState);
	}
	_prevCentury(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).subtract(100,'years'));
		this.setState(newState);
	}
	_nextCentury(e){
		let newState = this.state;
		newState.changeViewDate = this._initDate(moment(newState.changeViewDate).add(100,'years'));
		this.setState(newState);
	}
	_clearDate(e){
		this._stopPropagation(e);
		let newState = this.state;
		newState.initValue = '';
		newState.changeViewDate = this._initDate(new Date());
		this.setState(newState);
	}
	_selectDate(formDate){
		let newState = this.state;
		newState.initValue = formDate;
		newState.changeViewDate = formDate;
		newState.dateOpen = false;
		this.setState(newState);
		this.props.onChange?this.props.onChange(moment(formDate),formDate):"";
	}
	_selectMonth(formDate){
		let newState = this.state;
		newState.changeViewDate = formDate;
		newState.view = 'DatePicker';
		this.setState(newState);
	}
	_selectYear(formDate){
		let newState = this.state;
		newState.changeViewDate = formDate;
		newState.view = newState.previewView;
		this.setState(newState);
	}
	_selectDecade(formDate){
		let newState = this.state;
		newState.changeViewDate = formDate;
		newState.view = 'YearPicker';
		this.setState(newState);
	}
	_changeView(view,previewView){
		let newState = this.state;
		newState.view = view;
		newState.previewView = !!previewView?previewView:newState.previewView;
		this.setState(newState);
	}
	_renderDatePicker(){
		let that = this;
		let changeViewDate = that.state.changeViewDate;
		let format = that.state.format;
		const daysArr = [[], [], [], [], [], []];
		if(moment(changeViewDate).isValid()){
		 	const currentWeekday = moment(changeViewDate).date(1).weekday(); // 获取当月1日为星期几
		    const lastMonthDays = moment(changeViewDate).subtract(1, 'month').daysInMonth(); // 获取上月天数
		    const currentMonthDays = moment(changeViewDate).daysInMonth(); // 获取当月天数
		    const getDay = function(day){
		    	let formDate = '';
		    	let classType = '';
		    	let returnValue = '';
		    	// 上个月
		    	if(day <= lastMonthDays){
		    		formDate = moment(changeViewDate).subtract(1, 'month').date(day).format(format);
		    		classType = 'M-calendar-date-last-month-cell';
		    		returnValue = day;
		    	}else{
		    		// 这个月
		    		if(day <= (lastMonthDays + currentMonthDays)){
		    			formDate = moment(changeViewDate).date(day - lastMonthDays).format(format);
		    			moment(moment(new Date()).format(format)).diff(formDate,'days') == 0?
		    				moment(changeViewDate).diff(formDate,'days') == 0?
		    				classType = 'M-calendar-date-selected-day':classType = 'M-calendar-date-today':moment(changeViewDate).diff(formDate,'days') == 0?
		    				classType = 'M-calendar-date-selected-day':'';
		    			// if(moment(moment(new Date()).format(format)).diff(formDate,'days') == 0){
		    			// 	// console.log('这里是当天的日期',formDate);
		    			// 	classType = 'M-calendar-today';
		    			// 	if(moment(changeViewDate).diff(formDate,'days') == 0){
			    		// 		classType = 'M-calendar-selected-day';
			    		// 	}
		    			// }else if(moment(changeViewDate).diff(formDate,'days') == 0){
		    			// 	classType = 'M-calendar-selected-day';
		    			// 	// console.log('这里是指定的日期',formDate);
		    			// }
		    			returnValue =  day - lastMonthDays;
		    		}else{
		    		// 下个月
		    			formDate = moment(changeViewDate).add(1, 'month').date(day - (lastMonthDays + currentMonthDays)).format(format);
		    			classType = 'M-calendar-date-next-month-cell';
		    			returnValue =  day - (lastMonthDays + currentMonthDays)
		    		}
		    	}
		    	return {
		    		formDate,
		    		classType,
		    		returnValue
		    	};
		    }
		    for (let i = 0; i < 7; i += 1) {
		      let virtualDay = (lastMonthDays - currentWeekday) + i+1;
		      // 这里的作用就是处理日期的排列
		      for (let j = 0; j < 6; j += 1) {
		        daysArr[j][i] = getDay(virtualDay + (j * 7));
		      }
		    }
		    return (
		    	<div className={classNames('M-calendar-DatePicker')}>
		    		<div className={classNames('M-calendar-date-header M-calendar-header')}>
		    			<a title='Last Year' className={classNames('M-calendar-date-prev-year-btn')} onClick={that._prevYear}></a>
		    			<a title='Previous month' className={classNames('M-calendar-date-prev-month-btn')} onClick={that._prevMonth}></a>
		    			<span className={classNames('M-calendar-date-select')}>
		    				<a title='Choose a month' className={classNames('M-calendar-date-month-select')} onClick={that._changeView.bind(that,'MonthPicker')}>{moment.monthsShort()[moment(changeViewDate).month()]}</a>
		    				<a title='Choose a year' className={classNames('M-calendar-date-year-select')} onClick={that._changeView.bind(that,'YearPicker','DatePicker')}>{moment(changeViewDate).year()}</a>
		    			</span>
		    			<a title='Next month' className={classNames('M-calendar-date-next-month-btn')} onClick={that._nextMonth}></a>
		    			<a title='Next Year' className={classNames('M-calendar-date-next-year-btn')} onClick={that._nextYear}></a>
		    		</div>
		    		<div className={classNames('M-calendar-date-body M-calendar-tabel-parent')}>
		    			<table className={classNames('M-calendar-date-table')}>
		    				<thead>
		    					<tr>
		    					{
		    						moment.weekdaysShort().map(function(elem,index) {
		    							return (
		    								<td className={classNames('M-calendar-date-column-header')} key={`M-lendar-date-column-header-${index}`}>
		    									<span className={classNames('M-calendar-date-column-header-inner')}>{elem}</span>
		    								</td>
		    							);
		    						})
		    					}
		    					</tr>
		    				</thead>
		    				<tbody>
		    					{
		    						daysArr.map(function(elem,elemindex) {
		    							return (
		    								<tr key={`M-calendar-date-column-body-tr-${elemindex}`}>
		    									{elem.map(function(childElem,childElemindex) {
		    										return (
		    											<td title={childElem.formDate} className={classNames('M-calendar-cell',childElem.classType)} key={`M-calendar-date-column-body-td-${elemindex}-${childElemindex}`} onClick={that._selectDate.bind(that,childElem.formDate)}>
		    												<div className={classNames('M-calendar-date')}>{childElem.returnValue}</div>
		    											</td>
		    										);
		    									})}
		    								</tr>
		    							);
		    						})
		    					}
		    				</tbody>
		    			</table>
		    		</div>
		    	</div>
		    );
		}else{
			// 这里其实应该处理的更加友好一点
			console.log('这里是错误的日期格式');
			return false;
		}
	}
	_renderMonthPicker(){
		let that = this;
		let changeViewDate = that.state.changeViewDate;
		let format = that.state.format;
		if(moment(changeViewDate).isValid()){
			const MonthArr = moment.monthsShort(); // 获取月份的缩写
			let MonthRenderArr = [];
			let MonthIndex = 0;
			// 将一维数组变成二维数组然后进行循环
			while(MonthIndex < MonthArr.length){
				MonthRenderArr.push(MonthArr.slice(MonthIndex,MonthIndex+3));
				MonthIndex += 3;
			}
			return (
		    	<div className={classNames('M-calendar-MonthPicker')}>
		    		<div className={classNames('M-calendar-month-panel-header M-calendar-header')}>
		    			<a title='Last Year' className={classNames('M-calendar-month-panel-prev-year-btn')} onClick={that._prevYear}></a>
		    			<a title='Choose a year' className={classNames('M-calendar-month-panel-year-select')} onClick={that._changeView.bind(that,'YearPicker','MonthPicker')}>
		    				<span>{moment(changeViewDate).year()}</span>
		    			</a>
		    			<a title='Next Year' className={classNames('M-calendar-month-panel-next-year-btn')} onClick={that._nextYear}></a>
		    		</div>
		    		<div className={classNames('M-calendar-month-panel-body M-calendar-tabel-parent')}>
		    			<table className={classNames('M-calendar-month-panel-table')}>
		    				<tbody>
		    					{
		    						MonthRenderArr.map(function(elem,elemIndex) {
			    						return (
			    							<tr key={`M-calendar-month-column-body-tr-${elemIndex}`}>
			    							{
			    								elem.map(function(childElem,childElemIndex) {
		    										return (
		    											<td title={childElem} className={classNames('M-calendar-month-panel-cell',{'M-calendar-month-panel-selected-cell':childElem==MonthArr[moment(changeViewDate).get('month')]})} key={`M-calendar-month-column-body-td-${elemIndex}-${childElemIndex}`} onClick={that._selectMonth.bind(that,moment(changeViewDate).month(childElem).format(format))}>
		    												<a className={classNames('M-calendar-month-panel-month')}>{childElem}</a>
		    											</td>
		    										)
		    									})
	    									}
	    									</tr>
			    						)
			    					})
		    					}
		    				</tbody>
		    			</table>
		    		</div>
		    	</div>
		    );
		}else{
			// 这里其实应该处理的更加友好一点
			console.log('这里是错误的日期格式');
			return false;
		}
	}
	_renderYearPicker(){
		let that = this;
		let changeViewDate = that.state.changeViewDate;
		let format = that.state.format;
		if(moment(changeViewDate).isValid()){
			const CurrentYear = moment(changeViewDate).year(); // 获取当前的年份
			let CurrentDecade = parseInt(CurrentYear/10)*10;
			let CurrentDecadeLast = CurrentDecade + 9;
			let YearArr = [];
			let YearRenderArr = [];
			for(let i=0;i<=11;i++){
				YearArr.push(CurrentDecade+i-1);
			}
			let YearIndex = 0;
			// 将一维数组变成二维数组然后进行循环
			while(YearIndex < YearArr.length){
				YearRenderArr.push(YearArr.slice(YearIndex,YearIndex+3));
				YearIndex += 3;
			}
			return (
		    	<div className={classNames('M-calendar-YearPicker')}>
		    		<div className={classNames('M-calendar-year-panel-header M-calendar-header')}>
		    			<a title='Last Decade' className={classNames('M-calendar-year-panel-prev-decade-btn')} onClick={that._prevDecade}></a>
		    			<a title='Choose a decade' className={classNames('M-calendar-year-panel-decade-select')} onClick={that._changeView.bind(that,'DecadePicker',that.state.previewView)}>
		    				<span>{CurrentDecade}-{CurrentDecadeLast}</span>
		    			</a>
		    			<a title='Next Decade' className={classNames('M-calendar-year-panel-next-decade-btn')} onClick={that._nextDecade}></a>
		    		</div>
		    		<div className={classNames('M-calendar-year-panel-body M-calendar-tabel-parent')}>
		    			<table className={classNames('M-calendar-year-panel-table')}>
		    				<tbody>
		    					{
		    						YearRenderArr.map(function(elem,elemIndex) {
			    						return (
			    							<tr key={`M-calendar-year-column-body-tr-${elemIndex}`}>
			    							{
			    								elem.map(function(childElem,childElemIndex) {
		    										return (
		    											<td title={childElem} className={classNames('M-calendar-year-panel-cell',{'M-calendar-year-panel-selected-cell':childElem==moment(changeViewDate).year()},{'M-calendar-year-panel-last-decade-cell':childElem<CurrentDecade},{'M-calendar-year-panel-next-decade-cell':childElem>CurrentDecadeLast})} key={`M-calendar-month-column-body-td-${elemIndex}-${childElemIndex}`} onClick={that._selectYear.bind(that,moment(changeViewDate).year(childElem).format(format))}>
		    												<a className={classNames('M-calendar-year-panel-year')}>{childElem}</a>
		    											</td>
		    										)
		    									})
	    									}
	    									</tr>
			    						)
			    					})
		    					}
		    				</tbody>
		    			</table>
		    		</div>
		    	</div>
		    );
		}else{
			// 这里其实应该处理的更加友好一点
			console.log('这里是错误的日期格式');
			return false;
		}
	}
	_renderDecadePicker(){
		let that = this;
		let changeViewDate = that.state.changeViewDate;
		let format = that.state.format;
		if(moment(changeViewDate).isValid()){
			const CurrentYear = moment(changeViewDate).year(); // 获取当前的年份
			let CurrentCentury = parseInt(CurrentYear/100); // 获取世纪
			let CurrentCenturyDecade = CurrentCentury*100;	   // 获取当前世纪的首个年代
			let CenturyArr = [];
			let CenturyRenderArr = [];
			for(let i=0;i<=11;i++){
				let currentYearFirst = parseInt(CurrentCenturyDecade+(i-1)*10);
				let currentDecade = parseInt((CurrentCenturyDecade+(i-1)*10)/10);
				let currentCentery = parseInt(currentDecade/10);
				let decadeObj = {
					currentYearFirst,
					currentDecade,
					currentCentery,
					currentDecadeRange:`${currentYearFirst}-${currentYearFirst+9}`,
					classType:currentCentery > CurrentCentury?
								'M-calendar-decade-panel-next-century-cell':currentCentery < CurrentCentury?
									'M-calendar-decade-panel-last-century-cell':currentYearFirst<=CurrentYear&&CurrentYear<=(currentYearFirst+9)?
										'M-calendar-decade-panel-selected-cell':''
				}
				CenturyArr.push(decadeObj);//算出年代
			}
			let CenturyIndex = 0;
			// 将一维数组变成二维数组然后进行循环
			while(CenturyIndex < CenturyArr.length){
				CenturyRenderArr.push(CenturyArr.slice(CenturyIndex,CenturyIndex+3));
				CenturyIndex += 3;
			}
			return (
		    	<div className={classNames('M-calendar-DecadePicker')}>
		    		<div className={classNames('M-calendar-decade-panel-header M-calendar-header')}>
		    			<a title='Last Century' className={classNames('M-calendar-decade-panel-prev-century-btn')} onClick={that._prevCentury}></a>
		    			<a className={classNames('M-calendar-decade-panel-century-select')}>
		    				<span>{CurrentCenturyDecade}-{CurrentCenturyDecade+99}</span>
		    			</a>
		    			<a title='Next Century' className={classNames('M-calendar-decade-panel-next-century-btn')} onClick={that._nextCentury}></a>
		    		</div>
		    		<div className={classNames('M-calendar-decade-panel-body M-calendar-tabel-parent')}>
		    			<table className={classNames('M-calendar-decade-panel-table')}>
		    				<tbody>
		    					{
		    						CenturyRenderArr.map(function(elem,elemIndex) {
			    						return (
			    							<tr key={`M-calendar-decade-column-body-tr-${elemIndex}`}>
			    							{
			    								elem.map(function(childElem,childElemIndex) {
		    										return (
		    											<td className={classNames('M-calendar-decade-panel-cell',childElem.classType)} key={`M-calendar-decade-column-body-td-${elemIndex}-${childElemIndex}`} onClick={that._selectDecade.bind(that,moment(changeViewDate).year(childElem.currentYearFirst).format(format))}>
		    												<a className={classNames('M-calendar-decade-panel-decade')}>{childElem.currentDecadeRange}</a>
		    											</td>
		    										)
		    									})
	    									}
	    									</tr>
			    						)
			    					})
		    					}
		    				</tbody>
		    			</table>
		    		</div>
		    	</div>
		    );
		}else{
			// 这里其实应该处理的更加友好一点
			console.log('这里是错误的日期格式');
			return false;
		}
	}
	componentDidMount(){
    	ComponentTool.bind(document, 'click', this._closePicker);
  	}
  	componentWillUnmount(){
    	ComponentTool.unbind(document, 'click', this._closePicker);
  	}
	render(){
		let that = this;
		let initValue = !!that.state.initValue && moment(that.state.initValue).isValid()?that._initDate(that.state.initValue):that.state.initValue;
		let pickerContainerStay = this.props.pickerContainerStay? `M-calendar-picker-container-placement-${this.props.pickerContainerStay}`:'M-calendar-picker-container-placement-bottomLeft';
		return (
			<div className={classNames('M-calendar-picker',that.props.className,{'M-calendar-picker-open':that.state.dateOpen})}>
				<div onClick={that._showPicker} className={classNames('M-calendar-picker-input-area')}>
					<MInput value={initValue} placeholder={that.props.placeholder} readOnly/>
					<span className={classNames('M-calendar-picker-icon')} onClick={that._showPicker}><MIcon type='calendar' /></span>
					{!!that.state.initValue && moment(that.state.initValue).isValid()?<span className={classNames('M-calendar-picker-clear')} onClick={that._clearDate}><MIcon type='closecircle'/></span>:''}
				</div>
				{
					that.state.dateOpen?(
						<div onClick={that._stopPropagation} className={classNames('M-calendar-picker-container',pickerContainerStay)}>
							{
								that.state.view == 'DatePicker'?
									that._renderDatePicker():that.state.view == 'MonthPicker'?
										that._renderMonthPicker():that.state.view == 'YearPicker'?
											that._renderYearPicker():that.state.view == 'DecadePicker'?
												that._renderDecadePicker():''
							}
						</div>
					):''
				}
			</div>
		)
	}
}
DatePicker.MonthPicker = MonthPicker;
DatePicker.RangePicker = RangePicker;
module.exports = DatePicker;

/*
*	datePicker插件问题点:
*		1:需要根据传入的时间(其实在想是不是根据传入的format的格式会比较好)来进行年、月、日、时、分(秒有待考虑)组件的判断,而且默认是显示时间格式最后的时间对应的组件
*		3:日期格式的错误预防已经提示
*		4:目前这样写的方式是有问题的,很多东西都是可以重复用到的,考虑下是否可以整合起来
*		5:输入框传入的必须是value而不是defaultValue,因为改变日期的时候,如果输入框是defaultValue,state的日期变了，但是传倒MInput组件之后，日期却不会变,因此设置输入框直接不可点,这样最好处理
*		6:tabel的高度指定了的,这个有待修改
*		7:关闭的时候不能把关闭事件绑定到body上,如果绑定到body上的话则会出现点击内部日期插件都会关掉
*/